package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.RecordDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.learning.domain.CourseRecord;
import com.xuecheng.learning.mappers.CourseRecordMapper;
import com.xuecheng.learning.service.CourseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.search.api.SearchClient;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 选课记录 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-26
 */
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {

    @Autowired
    SearchClient searchClient;

    @Autowired
    ContentClient contentClient;

    @Autowired
    MediaClient mediaClient;

    //根据课程发布id，查询学生的学科数据
    @Override
    public ResponseResult findByCoursePubId(Long coursePubId) {
        //1.设置查询条件(用户id，课程发布id)
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId, AuthInfoHolder.getUserId());
        qw.eq(CourseRecord::getCoursePubId,coursePubId);
        //2.查询
        CourseRecord courseRecord = this.getOne(qw);
        //3.判断是否具有选课记录，如果没有返回空
        if (courseRecord == null) {
            return ResponseResult.okResult();
        }
        //4.构造返回
        CourseRecordVo vo = BeanHelper.copyProperties(courseRecord, CourseRecordVo.class);
        return ResponseResult.okResult(vo);
    }

    //保存或者更新选课记录
    @Override
    public ResponseResult saveRecord(RecordDto dto) {
        //0.判断(略)
        //1.查询选课记录
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getCoursePubId,dto.getCoursePubId());
        qw.eq(CourseRecord::getUserId,dto.getUserId());
        CourseRecord courseRecord = this.getOne(qw);
        boolean flag = false;
        if (courseRecord != null) {
            //1.1 选课记录存在，更新支付状态
            courseRecord.setPaid(OrdersConstants.PAID);
            flag = this.updateById(courseRecord);
        } else {
            //1.2 选课记录不存在，保存数据
            //2.根据请求参数-课程发布id，调用feign接口查询课程发布数据
            ResponseResult<CoursePubIndexVo> result = searchClient.findById(dto.getCoursePubId());
            CoursePubIndexVo vo = result.getData();
            courseRecord = new CourseRecord();
            courseRecord.setUserId(dto.getUserId());
            courseRecord.setCoursePubId(dto.getCoursePubId());
            courseRecord.setCompanyId(vo.getCompanyId());
            courseRecord.setCoursePubName(vo.getName());
            courseRecord.setCourseId(vo.getCourseId());
            courseRecord.setTeachmode(vo.getTeachmode());
            courseRecord.setCreateDate(new Date());
            courseRecord.setPaid(OrdersConstants.PAID);
            flag = this.save(courseRecord);
        }
        if (!flag) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        return ResponseResult.okResult();
    }

    //获取课程视频资源地址
    @Override
    public ResponseResult<ResourceVo> findPlayUrl(Long coursePubId, Long mediaId, Long teachplanId) {
        //1.查询课程发布数据
        ResponseResult<CoursePubIndexVo> pubResult = searchClient.findById(coursePubId);
        CoursePubIndexVo pubIndexVo = pubResult.getData();
        //2.判断课程是否是收费课程
        if (CourseConstants.CHARGE_YES.equals(pubIndexVo.getCharge())) {
            //3.收费课程，查询课程的当前章节
            ResponseResult<TeachplanVo> planResult = contentClient.findTeachPlanById(teachplanId);
            //4.判断当前章节是否收费
            TeachplanVo teachplanVo = planResult.getData();
            if ("0".equals(teachplanVo.getIsPreview())) {
                //5.如果当前章节收费，判断用户是否已经购买过此课程
                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
                qw.eq(CourseRecord::getCoursePubId,coursePubId);
                qw.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
                CourseRecord one = this.getOne(qw);
                if (one == null || one.getPaid() == OrdersConstants.NOT_PAID) {
                    throw new BusinessException(ErrorCode.NOTFOUND);
                }
            }
        }
        return mediaClient.findMediaUrl(mediaId);
    }

    //保存或者更新学习进度
    @Override
    public ResponseResult progress(LearningProgressDto dto) {
        //1.查询当前用户是否友课程的选课信息
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getCoursePubId,dto.getCoursePubId());
        qw.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
        CourseRecord one = this.getOne(qw);
        if (one != null) {
            //2.如果数据存在，更新章节
            one.setTeachplanId(dto.getTeachPlanId());
            one.setTeachplanName(dto.getTeachPlanName());
        } else {
            ResponseResult<CoursePubIndexVo> result = searchClient.findById(dto.getCoursePubId());
            CoursePubIndexVo vo = result.getData();
            //3.不存在，保存
            one = new CourseRecord();
            one.setUserId(AuthInfoHolder.getUserId());
            one.setCoursePubId(dto.getCoursePubId());
            one.setCompanyId(vo.getCompanyId());
            one.setCoursePubName(vo.getName());
            one.setCourseId(vo.getCourseId());
            one.setTeachmode(vo.getTeachmode());
            one.setCreateDate(new Date());
            one.setTeachplanId(dto.getTeachPlanId());
            one.setTeachplanName(dto.getTeachPlanName());
            one.setPaid(OrdersConstants.NOT_PAID);
        }
        return null;
    }
}
